<template>
	<view class="filter-advance-page">
		<!-- 自定義導航欄 -->
		<u-navbar
			:title="pageTitle"
			:border="false"
			:auto-back="true"
			:bg-color="'#FFFFFF'"
			:title-color="'#333333'"
			:title-size="36"
			:title-weight="'bold'"
			placeholder
		>
			<template #right>
				<u-icon name="more-dot-fill" size="20" color="#333" @click="showMoreOptions"></u-icon>
				<u-icon name="search" size="20" color="#333" @click="showSearch" style="margin-left: 20rpx;"></u-icon>
			</template>
		</u-navbar>

		<!-- 搜索欄 -->
		<view class="search-section">
			<view class="search-input-wrapper">
				<input
					v-model="keyword"
					placeholder="请输入关键词搜索"
					class="search-input"
					@input="searchExpenseItems"
				/>
				<text v-if="keyword" class="clear-btn" @click="clearSearch">×</text>
			</view>
		</view>

		<!-- 數據列表 -->
		<view class="data-list">
			<view 
				v-for="(item, index) in expenseItems" 
				:key="item.id"
				class="data-item"
				@click="selectExpenseItem(item)"
			>
				<view class="radio-wrapper">
					<view 
						class="radio"
						:class="{ 'radio-selected': selectedItem && selectedItem.id === item.id }"
						@click.stop="selectExpenseItem(item)"
					>
						<text v-if="selectedItem && selectedItem.id === item.id" class="radio-check">✓</text>
					</view>
					<view class="item-content">
						<text class="item-title">{{ item.fullName }}</text>
						<text class="item-number">{{ item.number }}</text>
					</view>
				</view>
			</view>
		</view>

		<!-- 底部操作按鈕 -->
		<view class="bottom-actions">
			<button class="btn btn-cancel" @click="cancel">
				取消
			</button>
			<button class="btn btn-confirm" @click="confirm">
				确定
			</button>
		</view>
	</view>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { borrowApi } from '@/api/api-helper.js'

// 頁面參數
const pageParams = ref({
	type: '',
	index: ''
})

// 费用项目列表
const expenseItems = ref([])
const loading = ref(false)
const keyword = ref('')
const currentPage = ref(1)
const pageSize = ref(20)
const total = ref(0)

// 选中的项目
const selectedItem = ref(null)

// 计算属性：页面标题
const pageTitle = computed(() => {
	return pageParams.value.type === 'expense' ? '选择费用项目' : '筛选'
})

// 按钮样式
const cancelBtnStyle = {
	backgroundColor: '#FFFFFF',
	borderColor: '#DDD',
	color: '#666666',
	fontSize: '32rpx',
	padding: '30rpx',
	borderRadius: '8rpx',
	flex: 1,
	marginRight: '10rpx'
}

const confirmBtnStyle = {
	backgroundColor: '#FF6B35',
	borderColor: '#FF6B35',
	color: '#FFFFFF',
	fontSize: '32rpx',
	padding: '30rpx',
	borderRadius: '8rpx',
	flex: 1,
	marginLeft: '10rpx'
}

// 方法
const showMoreOptions = () => {
	uni.showActionSheet({
		itemList: ['刷新', '设置', '帮助'],
		success: (res) => {
			console.log('选择了:', res.tapIndex)
		}
	})
}

const showSearch = () => {
	uni.showToast({
		title: '搜索功能',
		icon: 'none'
	})
}

// 页面加载时获取参数
onLoad((options) => {
	console.log('=== onLoad 触发 ===')
	console.log('页面参数 options:', options)
	
	// 直接从 options 获取参数
	if (options) {
		pageParams.value.type = options.type || ''
		pageParams.value.index = options.index || ''
	}
	
	console.log('筛选页面加载完成，pageParams:', pageParams.value)
	
	// 如果是费用项目选择模式，加载费用项目列表
	if (pageParams.value.type === 'expense') {
		loadExpenseItems()
	}
})

onMounted(() => {
	console.log('=== onMounted 触发 ===')
	console.log('筛选页面挂载完成')
})

// 加载费用项目列表
const loadExpenseItems = async (searchKeyword = '') => {
	loading.value = true
	try {
		const params = {
			keyword: searchKeyword,
			pageSize: pageSize.value,
			currentPage: currentPage.value
		}
		
		const response = await borrowApi.getLoadLists(params)
		if (response.code === 200) {
			// 根据新的接口返回格式处理数据
			const responseData = response.data
			expenseItems.value = responseData.list || []
			total.value = responseData.pagination?.total || 0
			
			console.log('费用项目列表数据:', expenseItems.value)
		} else {
			console.error('获取费用项目失败:', response.msg)
			uni.showToast({
				title: response.msg || '获取费用项目失败',
				icon: 'none'
			})
		}
	} catch (error) {
		console.error('获取费用项目失败:', error)
		uni.showToast({
			title: '网络错误',
			icon: 'none'
		})
	} finally {
		loading.value = false
	}
}

// 搜索费用项目
const searchExpenseItems = () => {
	currentPage.value = 1
	loadExpenseItems(keyword.value)
}

// 选择费用项目
const selectExpenseItem = (item) => {
	selectedItem.value = item
}

// 确认选择
const confirm = () => {
	console.log('=== confirm 方法触发 ===')
	console.log('selectedItem:', selectedItem.value)
	console.log('pageParams:', pageParams.value)
	
	if (!selectedItem.value) {
		uni.showToast({
			title: '请选择一个项目',
			icon: 'none'
		})
		return
	}
	
	// 将选中的项目存储到本地存储
	if (pageParams.value.type === 'expense') {
		const dataToStore = {
			expenseItem: selectedItem.value.fullName,
			expenseId: selectedItem.value.id,
			expenseNumber: selectedItem.value.number,
			detailIndex: pageParams.value.index
		}
		console.log('准备存储的数据:', dataToStore)
		
		try {
			uni.setStorageSync('expenseItemData', dataToStore)
			console.log('数据存储成功')
			
			// 验证存储是否成功
			const storedData = uni.getStorageSync('expenseItemData')
			console.log('验证存储的数据:', storedData)
		} catch (e) {
			console.error('存储数据失败:', e)
		}
	}
	
	// 返回上一页
	console.log('准备返回上一页')
	uni.navigateBack()
}

// 取消
const cancel = () => {
	uni.navigateBack()
}

// 清空搜索
const clearSearch = () => {
	keyword.value = ''
	currentPage.value = 1
	loadExpenseItems('')
}
</script>

<style lang="scss" scoped>
.filter-advance-page {
	background-color: #F5F5F5;
	min-height: 100vh;
	padding-bottom: 120rpx;
}

/* 搜索區域 */
.search-section {
	padding: 20rpx;
	background-color: #FFFFFF;
	border-bottom: 1rpx solid #F0F0F0;
}

.search-input-wrapper {
	position: relative;
	display: flex;
	align-items: center;
}

.search-input {
	flex: 1;
	padding: 20rpx;
	background-color: #F5F5F5;
	border-radius: 20rpx;
	border: none;
	font-size: 28rpx;
	color: #333;
}

.clear-btn {
	position: absolute;
	right: 20rpx;
	font-size: 32rpx;
	color: #999;
	cursor: pointer;
}

/* 數據列表 */
.data-list {
	padding: 20rpx;
}

.data-item {
	background-color: #FFFFFF;
	border-radius: 12rpx;
	margin-bottom: 20rpx;
	padding: 20rpx;
	cursor: pointer;
}

.radio-wrapper {
	display: flex;
	align-items: center;
}

.radio {
	width: 40rpx;
	height: 40rpx;
	border: 2rpx solid #DDD;
	border-radius: 50%;
	margin-right: 20rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	
	&.radio-selected {
		border-color: #FF6B35;
		background-color: #FF6B35;
	}
}

.radio-check {
	color: #FFFFFF;
	font-size: 24rpx;
	font-weight: bold;
}

.item-content {
	flex: 1;
}

.item-title {
	font-size: 28rpx;
	font-weight: 500;
	color: #333;
}

.item-number {
	font-size: 24rpx;
	color: #999;
	margin-top: 8rpx;
	display: block;
}

/* 底部操作按鈕 */
.bottom-actions {
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	padding: 20rpx;
	background-color: #FFFFFF;
	border-top: 1rpx solid #F0F0F0;
	display: flex;
	gap: 20rpx;
}

.btn {
	flex: 1;
	padding: 30rpx;
	border-radius: 8rpx;
	border: none;
	font-size: 32rpx;
	font-weight: bold;
}

.btn-cancel {
	background-color: #F5F5F5;
	color: #666;
}

.btn-confirm {
	background-color: #FF6B35;
	color: #FFFFFF;
}
</style>
